/*
 * Project Name: jmax
 * File Name: SocketServer.java
 * Copyright: Copyright(C) 1985-2015 ZKTeco Inc. All rights reserved.
 */
package com.xdtech.jmax.test;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import com.xdtech.socket.server.SocketUtil;

/**
 * TODO 一句话功能简述，请确保和下面的block tags之间保留一行空行
 * <p>
 * TODO 功能详细描述，若不需要请连同上面的p标签一起删除
 * 
 * @author <a href="max.zheng@zkteco.com">郑志雄</>
 * @version TODO 添加版本
 * @see 相关类或方法，不需要请删除此行
 * @since 2015-4-2 下午3:59:14
 */
public class SocketServer
{
	private ServerSocket ss;
	private Socket socket;
	private BufferedReader in;
	private PrintWriter out;

	public SocketServer() throws Exception
	{
		try
		{
			ss = new ServerSocket(9001);

			System.out.println("The server is waiting your input...");
			socket = ss.accept();
			socket.setSoTimeout(5000);	
			
			while (true)
			{
				
				in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				out = new PrintWriter(socket.getOutputStream(), true);
			    System.out.println("服务器端接受请求");  
				String line = in.readLine();

				System.out.println("you input is : " + line);

				out.println("\"success\":\"true\"");  

				out.close();
				in.close();
				socket.close();
				System.out.println("ttt");
				if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit"))
					break;
			}

			ss.close();

		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
		
		
//		ServerSocket serverSocket = new ServerSocket(9001);  
//		Socket socket = serverSocket.accept();  
//		while(true){//保持长连接  
//		    try {  
//		            Thread.sleep(100);//等待时间  
//		    } catch (InterruptedException e1) {  
//		            e1.printStackTrace();  
//		    }  
//		    if (socket !=null){  
//		        try {  
//	                String ip = socket.getInetAddress().toString().replace("/", "");  
//	                System.out.println("====socket.getInetAddress()====="+ip);  
//	                socket.setKeepAlive(true);  
//	                InputStream is = socket.getInputStream();  
//	                OutputStream os = socket.getOutputStream();  
//	                System.out.println("服务器端接受请求");  
//		            String tempdata = getContent(is);  
//		            System.out.println("接收到的数据为："+tempdata);  
//		            if(tempdata.contains("stop")){  
//		                is.close();  
//		                os.close();  
//		            }  
//		            os.flush();  
//		        }catch(Exception e){  
//		           System.out.println("出现了错误");
//		        }  
//		    }  
//		}  
	}

	/**
	 * 
	 * @author <a href="max.zheng@zkteco.com">郑志雄</>
	 * @since 2015-6-17 下午1:00:18
	 * @param is
	 * @return
	 */
	final static int BUFFER_SIZE = 4096;  
	private String getContent(InputStream in) throws Exception
	{
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] data = new byte[BUFFER_SIZE];  
        int count = -1;  
        while((count = in.read(data,0,BUFFER_SIZE)) != -1)  
            outStream.write(data, 0, count);  
          
        data = null;  
        return new String(outStream.toByteArray(),"UTF-8");  
	}

	public static void main(String[] args) throws Exception
	{
		new SocketServer().startServer();
	}

	/**
	 * 
	 * @author <a href="max.zheng@zkteco.com">郑志雄</>
	 * @since 2015-6-17 下午2:26:44
	 */
	private void startServer()
	{
		ServerSocket ss = null;
		try
		{
			ss = new ServerSocket(9000);
		}
		catch (IOException e1)
		{
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		while (true)
		{
			Socket socket = null;
			InputStream inputStream = null;
			OutputStream outputStream = null;
			boolean receiveSuccess = false;
			try
			{
				socket = ss.accept();
				socket.setSoTimeout(5000);
//				log.info("通信客户端ip="+socket.getInetAddress());
				inputStream = socket.getInputStream();
				outputStream = socket.getOutputStream();
//				BufferedReader in = new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
				
//				String line = in.readLine();
//				System.out.println("Web Server接收到上传数据：" + line);
				String reqStr = SocketUtil.readStrFromStream(socket
						.getInputStream());
				System.out.println("Web Server接收到上传数据：" + reqStr);
				
//				ReceiveHandler.handlerEvent(inetAddress.getHostAddress(),line);
				
				outputStream.write(("\nsuccess receive data="+reqStr).getBytes());
				receiveSuccess = true;
//				if (line.equalsIgnoreCase("quit") || line.equalsIgnoreCase("exit"))
//					break;
				
			}
			catch (Exception e)
			{
				receiveSuccess = false;
				e.printStackTrace();
				System.out.println("Monitoring Socket Server Error On Thread"+ e);
			}
			finally
			{
				System.out.println("finally");
				try
				{
					if (!receiveSuccess)
					{
						System.out.println("-----------fail");
						outputStream.write("\nconnect timeout not send data".getBytes());
					}
					if (null != inputStream)
					{
						inputStream.close();
					}
					if (null != outputStream)
					{
						outputStream.close();
					}
					if (null != socket)
					{
						socket.close();
					}
				}
				catch (IOException e)
				{
					e.printStackTrace();
					System.out.println("Monitoring Socket Server Close Error"+e);
				}
			}
		}
	}
}
